package swimv2gm.client.admin;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swimv2gm.bl.session.AbilityManager;
import swimv2gm.bl.session.ExistingDataException;

public class CreateAbility extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		AbilityManager man;
		try {
			man = (AbilityManager)InitialContext.doLookup("AbilityManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}
		if (request.getSession().getAttribute("admin") == null || !(Boolean)request.getSession().getAttribute("admin")) {
			response.sendError(403);
		}

		long aid = -1;
		try {
			aid = man.createAbility(request.getParameter("nome"),request.getParameter("descrizione"));
		} catch (ExistingDataException e) {
			response.sendRedirect("/SWIMv2gm/admin/addAbility.jsp?errortype=existing");
			return;
		}
		if (aid < 0) {
			response.sendRedirect("/SWIMv2gm/admin/addAbility.jsp?errortype=invalid");
		}
		else {
			response.sendRedirect("/SWIMv2gm/abilities/AbilityList");
		}
	}
}
